from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import uuid
from django.db.models import F


class FilterGoodsView(APIView):

    def get(self, request):

        sort = request.GET.get("sort")

        min = request.GET.get("min")
        max = request.GET.get("max")

        print("sort", sort)

        if sort:
            if sort == "1":
                # 我认为是 升序排列 根据价格
                queryset = Goods.objects.all().order_by("price")
            else:
                queryset = Goods.objects.all().order_by("-price")
        else:

            queryset = Goods.objects.filter(price__gt=min, price__lt=max)
        ser = GoodsSerializer(queryset, many=True)
        return Response(ser.data)


class GoodsView(APIView):

    def get(self, request):
        queryset = Goods.objects.all()
        ser = GoodsSerializer(queryset, many=True)
        return Response(ser.data)


class OrderView(APIView):

    def post(self, request):
        sn = uuid.uuid1().hex
        request.data["sn"] = sn
        ser = OrderSerializer(data=request.data)
        if ser.is_valid(raise_exception=False):
            ser.save()

            # 保存成功了 修改产品的 出游人数

            Goods.objects.filter(id=request.data.get("goods")).update(sale=F("sale") + 1)

            return Response({"msg": "OK"})
        else:
            print(ser.errors)
            return Response({"msg": "失败"})


class CommentView(APIView):

    def post(self, request):
        ser = CommentSerializer(data=request.data)
        if ser.is_valid(raise_exception=False):
            ser.save()

            # 保存成功了 修改产品的 评论数

            Goods.objects.filter(id=request.data.get("goods")).update(comments=F("comments") + 1)

            return Response({"msg": "OK"})
        else:
            print(ser.errors)
            return Response({"msg": "失败"})
